const fs = require('fs')
const path = require('path')
const { glob } = require('glob')

async function generateComponentTypes() {
  try {
    // 1. 查找所有组件目录
    const componentDirs = await glob('packages/components/*/', {
      ignore: ['**/node_modules/**']
    })

    const components = []

    // 2. 提取每个组件的props和emits类型信息
    for (const dir of componentDirs) {
      const name = path.basename(dir.replace(/\/$/, '')) // 移除尾部斜杠
      const propsFile = path.join(dir, 'src', `${name}.ts`)

      if (fs.existsSync(propsFile)) {
        components.push({
          name: `cms-${name}`,
          propsFile: path
            .relative(
              path.join(process.cwd(), 'packages/components'),
              propsFile
            )
            .replace(/\\/g, '/'),
          propsType: `${name.charAt(0).toUpperCase() + name.slice(1)}Props`,
          emitsType: `${name.charAt(0).toUpperCase() + name.slice(1)}Emits`
        })
      }
    }

    // 3. 生成类型声明内容
    let content = `// Auto-generated by generate-component-types.js\n`

    // 添加导入语句
    components.forEach(comp => {
      content += `import { ${comp.propsType}, ${
        comp.emitsType
      } } from './${comp.propsFile.replace('.ts', '')}'\n`
    })

    content += `\ndeclare module 'vue' {\n  export interface GlobalComponents {\n`

    // 添加组件声明
    components.forEach(comp => {
      content += `    '${comp.name}': {\n`
      content += `      $props: ${comp.propsType}\n`
      content += `      $emit: ${comp.emitsType}\n`
      content += `    }\n`
    })

    content += `  }\n}\n\nexport {}\n`

    // 4. 写入文件
    const outputPath = path.join(
      process.cwd(),
      'packages/components/components.d.ts'
    )
    fs.mkdirSync(path.dirname(outputPath), { recursive: true })
    fs.writeFileSync(outputPath, content)

    console.log(`Successfully generated ${outputPath}`)
  } catch (error) {
    console.error('Error generating component types:', error)
    process.exit(1)
  }
}

generateComponentTypes()
